//
//  RotatingView.swift
//  LeTu
//
//  Created by g1 on 2024/1/15.
//

import UIKit

class RotatingView: UIView {
    
    private let gcdTimer = AppGCDTimer.shared
    
    private var rotationAngle: CGFloat = 0.0
    private var animationDuration: TimeInterval = 2.0
    private var isPause = false
    
    init(duration: TimeInterval) {
        super.init(frame: .zero)
        animationDuration = duration
        addAppLifecycleObservers()
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addAppLifecycleObservers()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        addAppLifecycleObservers()
    }
    
    init(frame: CGRect, duration: TimeInterval) {
        super.init(frame: frame)
        animationDuration = duration
        addAppLifecycleObservers()
    }
    
    private func addAppLifecycleObservers() {
        NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: UIApplication.didEnterBackgroundNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(appWillEnterForeground), name: UIApplication.willEnterForegroundNotification, object: nil)
    }
    
    @objc private func appDidEnterBackground() {
        stopRotationAnimation()
    }
    
    @objc private func appWillEnterForeground() {
        if AppAudioManager.shared.isPlaying {
            resumeRotationAnimation()
        }
    }
    
    func startRotationAnimation() {
        
        if isPause == false {
            gcdTimer.scheduledDispatchTimer(WithTimerName: "rotationTimer", timeInterval: animationDuration / 360.0, queue: .main, repeats: true) { [weak self] in
                DispatchQueue.main.async {
                    self?.rotateView()
                }
            }
        } else {
            resumeRotationAnimation()
        }
        
    }
    
    private func rotateView() {
        rotationAngle += CGFloat.pi / 180.0
        transform = CGAffineTransform(rotationAngle: rotationAngle)
    }
    
    func resumeRotationAnimation() {
        if gcdTimer.isExistTimer(WithTimerName: "rotationTimer") {
            gcdTimer.startTimer(WithTimerName: "rotationTimer")
        } else {
            gcdTimer.scheduledDispatchTimer(WithTimerName: "rotationTimer", timeInterval: animationDuration / 360.0, queue: .main, repeats: true) { [weak self] in
                DispatchQueue.main.async {
                    self?.rotateView()
                }
            }
        }
    }
    
    func stopRotationAnimation() {
        isPause = false
        gcdTimer.cancelTimer(WithTimerName: "rotationTimer")
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
